package tree;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class VertexDemo {
    public static void main(String[] args) {
        int idCounter = 1;
        Vertex v1 = new Vertex(idCounter++);
        Vertex v2 = new Vertex(idCounter++);
        Vertex v3 = new Vertex(idCounter++);
        Vertex v4 = new Vertex(idCounter++);
        Vertex v5 = new Vertex(idCounter++);

        v1.addConnection(v4);
        v4.addConnection(v3);
        v3.addConnection(v2);
        v3.addConnection(v5);
        v2.addConnection(v4);
        bfs(v1);
    }

    public static void dfs(Vertex v) {
        visit(v);
        v.visited = true;
        for (Vertex va : v.adjacentVertices) {
            if (!va.visited) dfs(va);
        }
    }

    public static void bfs(Vertex v) {
        Queue<Vertex> q = new LinkedList<Vertex>();
        q.add(v);
        while (!q.isEmpty()) {
            Vertex vertex = q.remove();
            if (!vertex.visited) {
                visit(vertex);
                vertex.visited = true;
                q.addAll(vertex.adjacentVertices);
            }
        }
    }

    private static void visit(Vertex v) {
        System.out.println("Vertex: " + v.id);
    }

    private static class Vertex {
        private final int id;
        private boolean visited = false;
        private List<Vertex> adjacentVertices = new LinkedList<Vertex>();

        private Vertex(int id) {
            this.id = id;
        }

        public void addConnection(Vertex v) {
            adjacentVertices.add(v);
        }
    }
}
